<template>
  <el-container>
    <el-main>
      <!-- 意图列表区域 -->
      <div class="intentionContainer" v-show="triggerFlag">
            <avue-crud
              class="intention-table"
              :option="option"
              :data="data"
              :permission="permissionList"
              ref="crud"
              :page.sync="page"
              :table-loading="loading"
              @on-load="onLoad"
              @row-click="getOpenDetail"
              @select="select"
              @select-all="selectAll"
              @selection-change="selectionChange"
              :row-style="rowStyle"
            >
              <template slot="header">
                  <div id="kw-form-container">
                    <div class="kw-form-form">
                      <!-- 意图名称 -->
                      <el-input
                        :placeholder="$t('kwIntentionManage.intentionName')"
                        v-model="intentionName"
                        size="small"
                        clearable
                        class="kw-form-type"
                      >
                      </el-input>
                    </div>
                    <div class="kw-form-btn">
                      <el-button
                        type="primary"
                        icon="el-icon-search"
                        size="small"
                        class="kw-search-btn"
                        @click="handlerSearch"
                      ></el-button>
                      <el-button
                        size="small"
                        class="kw-reset-btn"
                        @click="handlerReset"
                      ><i class="aicosicon aicos-icon-clear"></i
                      ></el-button>
                    </div>
                  </div>
              </template>
              <template slot-scope="{ row }" slot="intentType">
                <!-- 问答类型 -->
                <div v-if="row.intentType == 1">
                  {{ $t("kwIntentionManage.answerType") }}
                </div>
                <!-- 任务类型 -->
                <div v-else>{{ $t("kwIntentionManage.taskType") }}</div>
              </template>
              <template slot-scope="{ row }" slot="trainingFlag">
                <!-- 已训练 -->
                <div v-if="row.trainingFlag == 1">
                  {{ $t("kwIntentionManage.hasTrain") }}
                </div>
                <div v-else>{{ $t("kwIntentionManage.readyTrain") }}</div>
              </template>
            </avue-crud>
      </div>
    </el-main>
    <el-aside width="260px" class="intention-right">
      <div class="selected-header">
        <span class="intention-header-left">已选意图</span>
        <el-button type="text" @click="removeAll">全部删除</el-button>
      </div>
      <el-form
        style="height: 320px"
        :model="selectForm"
        ref="dynamicValidateForm"
        class="demo-dynamic"
        @submit.native.prevent
      >
        <div class="checked-item">
          <el-form-item
            v-for="(item, index) in selectForm.selectArr"
            :key="index"
          >
            <div class="input-wrap">
              <span>{{item.intentName}}</span>
            </div>
            <el-button type="text" class="deleteFlag" @click="removeDomain(item,index)">移除</el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-aside>
  </el-container>
</template>
<script>
import LeftTree from "@/components/kwLeftTree/index";
import {
  intentList,
  intentDelete,
  batchDelete,
  batchSyncToEs,
  // intentionExport,
} from "@/api/kwKnowledgeCenter/kwIntention/index";
import { mapGetters } from "vuex";
import serviceList from "@/config/serviceList";
import { baseURL } from "@/api/common";
const { knowledge } = serviceList;
import QSGDrawer from "@/components/QSGDrawer/index";
export default {
  inject: ["desktopWindow", "desktop", "isRobotMenu"],
  props: {
    botId: {
      type: String,
      default: () => {
        return "";
      },
    },
  },
  data() {
    return {
      ids: [],
      sonCur: {},
      addSonIntentFlag: false,
      isEdit: false,
      cur: {},
      node: "",
      resolve: "",
      typeList: [
        { label: this.$t("kwIntentionManage.answerType"), value: "1" },
        { label: this.$t("kwIntentionManage.taskType"), value: "2" },
      ],
      statusList: [
        { label: this.$t("kwIntentionManage.hasTrain"), value: "1" },
        { label: this.$t("kwIntentionManage.readyTrain"), value: "0" },
      ],
      classifyId: "0", //分类id
      allWindowTopBodyHeight: 0, //窗口的高度
      classType: "intent",
      settingDrawer: false, //业务分类弹窗开关
      triggerFlag: true, //列表页和新建意图页进行切换
      intentionType: "", //问答类型
      intentionStatus: "", //训练状态
      intentionName: "", //意图名称
      data: [],
      page: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        pagerCount: 4,
      },
      option: {
        tip: false,
        selection: true,
        selectable:(row,index)=>{
            return row.$disabled != true;
        },
        reserveSelection:true,
        height: 315,
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        delBtn: false,
        searchBtn: false,
        columnBtn: false,
        refreshBtn: false,
        stripe: false,
        menu: false,
        menuAlign: "center",
        emptyText: this.$t('aicosCommon.notData'),
        column: [
          {
            label: this.$t("kwIntentionManage.intentionName"), //意图名称
            prop: "intentName",
            overHidden: true,
            html:true,
            formatter: (val, value, label) => {
              var showHtml = ''
              if (this.validatenull(value)) {
                showHtml = "--";
              } else if (val.numberQuote > 1) {
                //被引用
                showHtml = label + '<i class="el-icon-connection"></i>'
              } else if (val.createType == 1) {
                //引用
                showHtml = label + '<i class="el-icon-connection" style="color: red"></i>'
              } else {
                showHtml = label
              }
              return showHtml;
            },
          },
        ],
      },
      addType: "",
      selectForm: {
        selectArr: [],
      }
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      const prefix = this.isRobotMenu ? "robot-" : "";
      return {
        addBtn: this.vaildData(
          this.permission[`${prefix}intention-add`],
          false
        ),
        delBtn: this.vaildData(
          this.permission[`${prefix}intention-delete`],
          false
        ),
        editBtn: this.vaildData(
          this.permission[`${prefix}intention-edit`],
          false
        ),
        childrenBtn: this.vaildData(
          this.permission[`${prefix}intention-addchildren`],
          false
        ),
        deleteMoreBtn: this.vaildData(
          this.permission[`${prefix}intention-deleteMore`],
          false
        ),
        exportBtn: this.vaildData(
          this.permission[`${prefix}intention-export`],
          false
        ),
        syncBtn: this.vaildData(
          this.permission[`${prefix}intention-batchSyncToEs`],
          false
        ),
        importBtn: this.vaildData(
          this.permission[`${prefix}intention-import`],
          false
        ),
      };
    },
  },
  components: {
    LeftTree,
    QSGDrawer,
  },
  methods: {
    async onLoad() {
      this.loading = true;
      this.data = [];
      const info = {
        botId: this.botId,
        classifyId: this.classifyId,
        current: this.page.currentPage,
        size: this.page.pageSize,
        intentName: this.intentionName, //意图名称
        intentType: this.intentionType, //意图类型
        trainingFlag: this.intentionStatus, //训练状态
      };
      const result = await intentList(info);
      if (result.data.code == 200) {
        this.data = result.data.data.records;
        this.page.total = result.data.data.total;
        this.loading = false;
      }
    },
    nodeClick(data) {
      this.classifyId = data;
      this.onLoad();
    },
    //动态获取窗口大小
    desktopWindowResize() {
      this.allWindowTopBodyHeight =
        this.desktopWindow.$el.getElementsByClassName(
          "desk-window-inner"
        )[0].offsetHeight;
    },
    //获取树的node和resolve
    getNode(data) {
      this.node = data.node;
      this.resolve = data.resolve;
    },
    //搜索
    handlerSearch() {
      this.onLoad();
      setTimeout(() => {
        this.loading = true;
        this.listIsExpand(this.data, true);
        this.loading = false;
      }, 100);
    },
    //重置
    handlerReset() {
      this.intentionName = "";
      this.intentionType = "";
      this.intentionStatus = "";
      this.onLoad();
      this.listIsExpand(this.data, false);
    },
    //列表树的展开收起
    listIsExpand(arr, expandFlag) {
      this.loading = true;
      arr.forEach((item) => {
        this.$refs.crud.toggleRowExpansion(item, expandFlag);
        if (item.children) {
          this.listIsExpand(item.children, expandFlag);
        }
      });
      this.loading = false;
    },

    // 设置父级选中/取消
    setParent(currentRow, type, parent, selectionLists) {
      if (!parent.length) {
        parent = this.data;
      }
      parent.forEach((item) => {
        if (item.children&&item.children.length>0) {
          // 注：ancestors是当前选中节点的所有父节点的一个字符串形式的数据，这个很关键
          if ((currentRow.topNode === item.id||(currentRow.topNode === item.topNode&&currentRow.topNode !==null)||currentRow.id ==item.id)) {
            // 选中
            if(type && (currentRow.id !=item.id)) {
              item.$disabled = true
            } else {
              item.$disabled = false
            }
            if(item.children&&item.children.length >0) {
              this.setParent(currentRow, type, item.children, selectionLists);
            }
          }
        }
      });
    },
    // 选中父节点时，子节点一起选中取消
    select(selection, row) {
      const hasSelect = selection.some((el) => {
        return row.id === el.id;
      });
      if (hasSelect) {
        //选中父级，将其下所有子级置灰
        if (row.children&&row.children.length>0) {
          this.tableDataHandle(this.data,  0, row, '')
        }
        if((row.topNode === null&&row.children&&row.children.length>0)||(row.topNode !== null)) {
          // 子级选中, 如果当前的同级都选中了，则父级就选中了(目前只做到父级选中，爷爷级选不中)
          this.setParent(row, true, [], selection);
        }
      } else {
        //取消选中父级，将其下所有子级取消置灰
        if (row.children&&row.children.length>0) {
          this.tableDataHandle(this.data,0,row,'no')
        }
        // 子级取消选中, 传入当前选中节点, 所有父级取消选中
        this.setParent(row, false, []);
      }
    },

    tableDataHandle(arr, level = 0,row,type) {
      level = level + 1;
      arr.map((item, idx) => {
        item.level = level;
        if(type == 'disabled'&&item.topNode!==null) {
          item.$disabled = true
        } else if(type == 'nodisabled'&&item.topNode!==null) {
          item.$disabled = false
        }
        if(item.id == row.id&&type =='') {
          type = 'disabled'
        } else if (item.id == row.id&&type =='no') {
          type = 'nodisabled'
        }
        if (item.children) {
          this.tableDataHandle(item.children, level,row,type);
        }
      });
      return arr;
    },

    // 选择全部
    selectAll(selection) {
      // data第一层只要有在selection里面就是全选
      const isSelect = selection.some((el) => {
        const tableDataIds = this.data.map((j) => j.id);
        return tableDataIds.includes(el.id);
      });
      // data第一层只要有不在selection里面就是全不选
      const isCancel = !this.data.every((el) => {
        const selectIds = selection.map((j) => j.id);
        return selectIds.includes(el.id);
      });
      if (isSelect) {
        selection.map((el) => {
          if (el.children) {
            // 解决子组件没有被勾选到
            this.setChildren(el.children, true);
          }
        });
      }
      if (isCancel) {
        this.data.map((el) => {
          if (el.children) {
            // 解决子组件没有被勾选到
            this.setChildren(el.children, false);
          }
        });
      }
    },

    //获取选中数据
    selectionChange(value) {
      var idArr = [];
      value.forEach((item) => {
        idArr.push(item.id);
      });
      this.ids = [...new Set(idArr)];
      this.selectForm.selectArr = value
    },
    removeDomain(item,index) {
      this.selectForm.selectArr.splice(index,1)
      this.$refs.crud && this.$refs.crud.toggleRowSelection(item, false);
      this.select(this.selectForm.selectArr,item)
    },
    removeAll() {
      this.selectForm.selectArr.forEach(item=>{
        this.$refs.crud && this.$refs.crud.toggleRowSelection(item, false);
        this.select(this.selectForm.selectArr,item)
      })
      this.selectForm.selectArr = []
    }
  },
  mounted() {
    if (this.desktopWindow) {
      //获取窗口的大小
      this.allWindowTopBodyHeight =
        this.desktopWindow.$el.getElementsByClassName(
          "desk-window-inner"
        )[0].offsetHeight;
      //监听窗口变化,重新获取新的窗口大小
      this.desktopWindow.$on("resize", this.desktopWindowResize);
    }
  },
  beforeDestroy() {
    if (this.desktopWindow) {
      this.desktopWindow.$off("resize", this.desktopWindowResize);
    }
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-card__body {
  padding: 0;
}

/deep/ .avue-crud__menu {
  display: none;
}
.selected-header {
  height: 35px;
  display: flex;
  justify-content: space-between;
}
#kw-form-container {
  padding-top: 0px;
}
/deep/.avue-crud__pagination {
  padding-left: 0px;
  .el-pagination {
    padding: 2px 0px;
  }
  .el-pagination__jump {
    margin-left: 0;
  }
  .el-pagination__sizes {
    margin: 0;
  }
  .el-pagination.is-background .btn-next, .el-pagination.is-background .btn-prev, .el-pagination.is-background .el-pager li {
    margin: 0 2px;
  }
  .el-pagination .el-select .el-input .el-input__inner {
    padding-right: 18px
  }
  .el-pagination .el-select .el-input {
    width: 80px;
    margin: 0 3px;
  }
  .el-pagination__total {
    margin-right: 0px
  }
}
.intention-right {
  width: 260px;
  background-color: #F7F9FB;
  padding: 10px 20px;
  margin-left: 10px;
  border-radius: 10px;
}
.intention-header-left {
  display: inline-block;
  height: 35px;
  line-height: 35px;
}
.checked-item {
  .el-form-item {
    margin-bottom: 0px;
  }
}
.input-wrap {
  width: 170px;
  display: inline-block;
  margin-right: 10px;
}

/* 隐藏表格左上角复选框 */
.page ::v-deep .el-table__fixed-header-wrapper .el-checkbox__inner {
  display: none !important;
}
</style>
